package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollUtil;
import com.itheima.domain.mongo.Friend;
import com.itheima.domain.mongo.FriendMovement;
import com.itheima.domain.mongo.MyMovement;
import com.itheima.service.mongo.FriendService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FriendServiceImpl implements FriendService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public void saveContact(Long userId, Long friendId) {
        //我加对方
        //添加之前要先判断一下数据库中有无此数据,若无再添加
        //将对方的动态存入我的好友动态中
        if (!isFriend(userId,friendId)) {
            addFriendMovement(userId, friendId);
        }

        //对方加我
        if (!isFriend(friendId,userId)) {
            addFriendMovement(friendId,userId);
        }
    }

    @Override
    public PageBeanVo findContactsByPage(Long userId, Integer pageNum, Integer pageSize) {
        //1.创建条件对象
        Query query = new Query(Criteria.where("userId").is(userId)).skip((pageNum - 1) * pageSize).limit(pageSize);
        //2.查询好友表
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        Long counts = CollUtil.isEmpty(friends)?0L:friends.size();
        return new PageBeanVo(pageNum,pageSize,counts,friends);
    }

    //判断user1是否添加了user2
    private boolean isFriend(Long user1,Long user2){
        return mongoTemplate.exists(new Query(Criteria.where("userId").is(user1).and("friendId").is(user2)), Friend.class);
    }

    //将user2的动态加入到user1的好友动态中
    private void addFriendMovement(Long user1,Long user2){
        //1.查询user2的动态list
        List<MyMovement> movementList = mongoTemplate.findAll(MyMovement.class, ConstantUtil.MOVEMENT_MINE + user2);

        //2.遍历动态list,获取每个动态,将动态封装成好友动态,存放user1的好友动态中
        if (CollUtil.isNotEmpty(movementList)) {
            for (MyMovement myMovement : movementList) {
                FriendMovement friendMovement = new FriendMovement();
                friendMovement.setUserId(user2);
                friendMovement.setPublishId(myMovement.getPublishId());
                friendMovement.setCreated(myMovement.getCreated());

                mongoTemplate.save(friendMovement,ConstantUtil.MOVEMENT_FRIEND+user1);
            }
        }

        //3.保存好友
        Friend friend = new Friend();
        friend.setUserId(user1);
        friend.setFriendId(user2);
        friend.setCreated(System.currentTimeMillis());
        mongoTemplate.save(friend);
    }
}
